import {designPage, reactive, useRefs} from "plain-design-composition";
import data from '../../../data/data-1.json';
import {$message, Adc, AdcColorPicker, AdcDate, AdcIndex, AdcInput, AdcInputNumber, AntdTable, Button, ButtonGroup, DatePicker, Form, FormItem, iAdtCellRenderScope, iAdtNode, iAdtRowRenderScope, Segment, SegmentGroup, Switch} from "../../../../packages";
import {DemoRow} from "../../Demo/DemoRow";
import {iValidatorParam} from "../../../../packages/components/Form/validate/validate.utils";
import {PlainObject} from "plain-utils/utils/event";
import {deepcopy} from "plain-utils/object/deepcopy";
import {FixInput} from "../../../../packages/utils/FixInput";

export const demo1 = designPage(() => {

  const { refs, onRef } = useRefs({ table: AntdTable });

  const state = reactive({
    size: undefined as any,
    data: data as any[],
    editNodes: [] as iAdtNode[],
    virtualFlag: false,
    formEdit: false,
    associateFields: {
      name: 'size',
    },
    isEditable: ({ state: { editRow } }: iAdtNode) => !!editRow.name && editRow.name.length > 5,
    isRequired: (formData: PlainObject | null | undefined) => !!formData?.name && formData.name.length > 5,
    customRule: {
      validator: ({ formData }: iValidatorParam) => {
        if (!formData) {return; }
        return !!formData.name && formData.name.length > 5 ?
          (!formData.size && formData.size !== 0) ? 'name 长度大于5情况下必填' : undefined
          : undefined;
      }
    },
    onDblClickRow({ node: tableNode }: iAdtRowRenderScope) {
      if (state.formEdit) {
        refs.table!.formEditor.methods.edit({
          node: tableNode,
          onConfirm: (node) => {
            state.data[tableNode.state.index] = deepcopy(node.state.editRow);
          }
        });
      } else {
        if (!tableNode.state.edit) {
          tableNode.enableEdit();
          state.editNodes.push(tableNode);
        }
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <div>
      <DemoRow title={'基本用法'}>
        <Form column={1}>
          <FormItem label="大小尺寸">
            <SegmentGroup v-model={state.formEdit}>
              <Segment label="行内编辑" val={false}/>
              <Segment label="表单编辑" val={true}/>
            </SegmentGroup>
          </FormItem>
          <FormItem label="大小尺寸">
            <SegmentGroup v-model={state.size}>
              <Segment label="Mini" val="mini"/>
              <Segment label="Small" val="small"/>
              <Segment label="Normal" val="normal"/>
              <Segment label="Large" val="large"/>
            </SegmentGroup>
          </FormItem>
          <FormItem label={'是否开启虚拟滚动'}>
            <Switch v-model={state.virtualFlag}/>
          </FormItem>
          <FormItem label={'编辑'}>
            <ButtonGroup disabled={state.editNodes.length === 0}>
              <Button onClick={state.saveEdit} label={'保存编辑'}/>
              <Button onClick={state.cancelEdit} label={'取消编辑'}/>
            </ButtonGroup>
          </FormItem>
        </Form>
      </DemoRow>
      <DemoRow title={'行内编辑'}>
        <AntdTable
          showRows={10}
          virtual={state.virtualFlag}
          dataSource={state.data}
          onRowDoubleClick={state.onDblClickRow}
          ref={onRef.table}
          pagination={false}
        >
          <AdcIndex/>
          <Adc dataIndex="id" title="编号" width={50}/>
          <Adc dataIndex="name" title="普通文本列"/>
          <Adc dataIndex="name" title="普通文本列，编辑作用域插槽" width={200} editable={state.isEditable}
               render={{
                 edit: ({ row }) => (
                   <FixInput type="text" v-change={row.name} style={{ paddingLeft: '8px' }}/>
                 )
               }}
          />
          <AdcInput dataIndex="name" title="禁用编辑" editable={false}/>
          <AdcInput dataIndex="name" title="文本框" required/>
          <AdcInput dataIndex="size" title="文本框值大于6可以编辑" width={200} editable={state.isEditable} rules={state.customRule}/>
          <AdcInputNumber dataIndex={'size'} title={'数字框'} required={state.isRequired}/>
          <AdcDate dataIndex={'date'} title={'日期'}/>
          <AdcDate dataIndex={'dateStart'} title={'开始日期'} formLabel="日期范围" editColSpan={2}
                   render={{
                     edit: ({ row }: iAdtCellRenderScope) => (
                       <DatePicker v-model:start={row.dateStart} v-model:end={row.dateEnd} range/>
                     ),
                   }}
          />
          <AdcDate dataIndex={'dateEnd'} title={'结束日期'} editColSpan={0}/>
          <AdcColorPicker dataIndex={'color'} title={'颜色'}/>
          {/*<AdcRate dataIndex={'star'} title={'评分'}/>*/}
        </AntdTable>
      </DemoRow>
    </div>
  );
});
